package service;

import com.sun.net.httpserver.HttpServer;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;

import service.functions.FunctionService;
import service.xml.ServiceResponse;

import java.io.IOException;
import java.util.ArrayList;

import javax.ws.rs.*;
import javax.ws.rs.core.Response;

import javax.xml.bind.JAXBElement;

/**
 * Created with IntelliJ IDEA.
 * User: Claudio "Dna" Bonesana
 * Date: 20.03.13
 * Time: 08:49
 */

@Path("/")
public class WeatherWebService {

    static public final String acronym = "WeatherWebService";
    static public final int port = 9998;

    static ServiceStatus serviceStatus;

    public static void main(String[] args) throws IOException {

        try {
            serviceStatus = new ServiceStatus();
        } catch (StatusException e) {
            e.printStackTrace();
            System.exit(200);
        }

        // Create a new HTTP server
        HttpServer server = HttpServerFactory.create(serviceStatus.getUri());
        server.start();

        // Create update task
        ServiceUpdater updater = new ServiceUpdater(serviceStatus,60);
        updater.startTimer();

        System.out.println("Server is running");
        System.out.println("Visit: http://localhost:"+port+"/"+ acronym);
        System.out.println("Hit return to stop...");
        System.in.read();
        System.out.println("Stopping server");

        server.stop(0);
        System.out.println("Server stopped");

        System.exit(0);
    }


    @GET
    @Produces("text/html")
    public String getHome(){
        return "<html><h1 style=\"color:red\">" + acronym + "</h1></html>";
    }

    @GET
    @Path("/data")
    @Produces("text/xml")
    public Response getClichedMessage() {

        System.out.println("GET request!");

        ServiceResponse response = serviceStatus.getData();

        return Response.status(200).entity(response).build();
    }

    @POST
    @Path("/set")
    @Consumes("text/xml")
    @Produces("text/xml")
    public String getPostedMessage(JAXBElement<ServiceResponse> param) {

        System.out.println("POST request!");

        // Parsing of input XML
        ServiceResponse sr = param.getValue();
        ArrayList<FunctionService> sf = sr.getFunctions();

        try {

            // Execution of local functions
            serviceStatus.updateStatus(sf);

            return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                    "<Response>\n" +
                    "  <Code>0</Code>\n" +
                    "  <Message>ok</Message>\n" +
                    "</Response>";

        } catch (StatusException e) {
            // Update status failed
            return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                    "<Response>\n" +
                    "  <Code>101</Code>\n" +
                    "  <Message>" + e.getMessage() + "</Message>\n" +
                    "</Response>";

        }

    }
}